package com.example.api;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RefreshScope
public class DemoAction {

    private final Logger logger = Logger.getLogger(getClass());

    @Value("${from}")
    private String from;
    
    @Autowired
    private DiscoveryClient client;
    
    @Autowired
    private RestTemplate restTemplate;
    
    @RequestMapping(value = "/add")
    public String add(@RequestParam Integer a, @RequestParam Integer b) {
        ServiceInstance instance = client.getLocalServiceInstance();
        Integer r = a + b;
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
        return "From Service-A,  Result is " + r;
    }
    
    @RequestMapping(value = "/")
    public String hello(String name) {
    	String greet = "Hello %s, from "+from+".";
    	name =  StringUtils.isEmpty(name) ? "World" : name;
    	
        return String.format(greet, name);
    }

    /*//A服务调用B服务
    @RequestMapping(value="testServiceB",method=RequestMethod.GET)
    public String testServiceB(@RequestParam Integer a,@RequestParam Integer b){
    	return restTemplate.getForObject("http://localhost:7075/add?a="+a+"&b="+b, String.class);
    }*/
    
}